package org.tio.showcase.test;

import org.tio.websocket.client.WebSocket;
import org.tio.websocket.client.WsClient;
import org.tio.websocket.client.config.WsClientConfig;
import org.tio.websocket.common.WsPacket;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Pattern;

/**
 * https://www.tiocloud.com/tio/docs/t-io/demo/tiowsc/
 *
 * @author chenck
 * @date 2025/3/11 16:45
 */
public class FileWebSocketClient {

    public static void main(String[] args) throws Exception {
        Map<Integer, Boolean> sent = new ConcurrentHashMap<>();

        // encoding=BINARY or text 不影响传文件
        WsClient echo =
                WsClient.create(
                        "ws://localhost:9326/?encoding=BINARY",
                        new WsClientConfig(
                                e -> System.out.println("opened"),
                                e -> {
                                    WsPacket data = e.data;
                                    String dataStr = data.getWsBodyText();
                                    System.out.println("recv: " + dataStr);
                                },
                                e -> System.out.printf("on close: %d, %s, %s\n", e.code, e.reason, e.wasClean),
                                e -> System.out.println(String.format("on error: %s", e.msg)),
                                Throwable::printStackTrace));

        WebSocket webSocket = echo.connect();

        // 读取音频文件并发送字节流
        // 如果是文件，直接一次性发送完
        byte[] audioData = Files.readAllBytes(Paths.get("D:\\workspace\\github\\video.mp4"));
        webSocket.send(audioData);

        // 分块发送字节流
        int chunkSize = 8192; // 每次发送8KB的数据
        for (int i = 0; i < audioData.length; i += chunkSize) {
            int end = Math.min(i + chunkSize, audioData.length);
            byte[] chunk = Arrays.copyOfRange(audioData, i, end);
            webSocket.send(chunk);
        }
    }
}
